package com.wxx.service.tool.ucpaas;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.wxx.common.Const;
import com.wxx.model.sdk.Ucpaas;
import com.wxx.model.sdk.UcpaasJson;
import com.wxx.sdk.ucpaas.client.AbsRestClient;
import com.wxx.sdk.ucpaas.client.JsonReqClient;
import com.wxx.util.PropertiesUtil;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class UcpaasServiceImpl implements UcpaasService {

    static AbsRestClient InstantiationRestAPI() {
        return new JsonReqClient();
    }
    @Override
    public Map sendSms(Ucpaas ucpaas) {
        Map map=null;
        try {
            String result = InstantiationRestAPI().sendSms(
                    PropertiesUtil.getProperty("UCPAAS_SID"),
                    PropertiesUtil.getProperty("UCPAAS_TOKEN"),
                    PropertiesUtil.getProperty("UCPAAS_APPID"),
                    ucpaas.getTemplateid(),
                    ucpaas.getParam(),
                    ucpaas.getMobile(),
                    ucpaas.getUid());

           map = (Map) JSON.parse(result);
           System.out.println("Response content is: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    @Override
    public Map sendSmsBatch(Ucpaas ucpaas) {
        Map map=null;
        try {
            String result = InstantiationRestAPI().sendSmsBatch(
                    PropertiesUtil.getProperty("UCPAAS_SID"),
                    PropertiesUtil.getProperty("UCPAAS_TOKEN"),
                    PropertiesUtil.getProperty("UCPAAS_APPID"),
                    ucpaas.getTemplateid(),
                    ucpaas.getParam(),
                    ucpaas.getMobile(),
                    ucpaas.getUid());

            map = (Map) JSON.parse(result);
            System.out.println("Response content is: " + result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public Map sendSmsInternational(UcpaasJson ucpaasJson) {
        //用户的账号唯一标识“Account Sid”，在开发者控制台获取
        String ucpaasSid = PropertiesUtil.getProperty("UCPAAS_SID");
        String url= "https://api.ucpaas.com/2014-06-30/Accounts/"+ucpaasSid+"/Messages/templateSMS?sig=";

        //设置appid
        ucpaasJson.setAppId(PropertiesUtil.getProperty("UCPAAS_APPID"));
        ucpaasJson.setTemplateId(PropertiesUtil.getProperty("SEND_CODE_TEMPLATE_ID"));

        //设置好json格式
        Map map = Maps.newHashMap();
        map.put("templateSMS",ucpaasJson);
        String jsonString = JSON.toJSONString(map);
//        System.out.println(jsonString);

        //获取时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        //两组参数分别为账户ID Account Sid 跟  Auth Token
        String s = PropertiesUtil.getProperty("UCPAAS_SID") + PropertiesUtil.getProperty("UCPAAS_TOKEN") + date;
        try {
            s = this.EncodeByMd5(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url = url + s;

        //设置Authorization信息   ****代表Account Sid

        s = PropertiesUtil.getProperty("UCPAAS_SID") + ":" + date;
        try {
            s=this.EncodeByBase64(s);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("host", "api.ucpaas.com");
            conn.setRequestProperty("accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("Authorization", s);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(jsonString);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        map = (Map) JSON.parse(result);
        String resp1 = map.get("resp").toString();
        Map resp = (Map) JSON.parse(resp1);

        Map map1 = Maps.newHashMap();
        if ("000000".equals(resp.get("respCode"))){
            map1.put("code", Const.SUCCESS_CODE);
            map1.put("body", map);
        }else{
            map1.put("code", Const.ERROR_CODE);
            map1.put("body", map);
        }

        System.out.println("Response content is: " + map1);

        return map1;
    }

    public static String EncodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        //获取数据
        md5.update(str.getBytes());
        //根据API要求获取32位MD5加密
        String newstr=new BigInteger(1, md5.digest()).toString(16);
        newstr=newstr.toUpperCase();
        return newstr;
    }

    public static String EncodeByBase64(String str) throws UnsupportedEncodingException {

        BASE64Encoder base64en = new BASE64Encoder();
        String newstr = base64en.encode(str.getBytes());
        return newstr;
    }


    /**
     * 测试发送国际短信
     * @param args
     */
    public static void main(String[] args) {
        UcpaasJson ucpaasJson = new UcpaasJson();
        ucpaasJson.setTo("17512580833");
        ucpaasJson.setParam("666");
        Map map = new UcpaasServiceImpl().sendSmsInternational(ucpaasJson);
        System.out.println(map);
    }
}
